package com.scs.application.modules.base.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Maps;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.mvc.controller.CrudController;
import com.scs.application.core.query.QueryContext;
import com.scs.application.core.query.QueryContextHolder;
import com.scs.application.core.threadLock.ThreadLock;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.base.dto.WarehouseSelectDto;
import com.scs.application.modules.base.entity.Dept;
import com.scs.application.modules.base.entity.Location;
import com.scs.application.modules.base.entity.Warehouse;
import com.scs.application.modules.base.mapper.WarehouseMapper;
import com.scs.application.modules.base.service.DeptService;
import com.scs.application.modules.base.service.LocationService;
import com.scs.application.modules.base.service.WarehouseService;
import com.scs.application.modules.report.handler.BeforeReport;
import com.scs.application.modules.sys.model.PageResult;
import com.scs.application.modules.sys.model.RestResult;
import com.scs.application.modules.wm.entity.Stock;
import com.scs.application.modules.wm.service.StockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 */
@RestController
@RequestMapping("/base/warehouse")
public class WarehouseController extends CrudController<WarehouseService, Warehouse>{
    @Autowired
    StockService stockService;

    @Autowired
    LocationService locationService;

    @Autowired
    DeptService deptService;

    @Resource
            @Lazy
    WarehouseMapper warehouseMapper;
    /**
     * 获取带有中心仓库属性的仓库
     * @return
     */
    @GetMapping("/getCenter")
    public RestResult getCenterWarehouse() {
       return RestResult.ok("获取数据成功", service.list(new QueryWrapper<Warehouse>().eq("flag_center", 1)));
    }


    /**
     * @Description：设置科室或者用户仓库权限的数据源
     */
    @GetMapping("/getListForSetWarehouse")
    public RestResult<List> getListForSetWarehouse(@RequestParam String id,@RequestParam String setTypeField) {
        List result = service.getListForSetWarehouse(setTypeField,id);
        return RestResult.ok("查询成功", result);
    }


    /**
     * 添加/更新数据
     */
    @PostMapping("/save")
    public RestResult saveItem(@Valid @RequestBody Warehouse entity) {
        if (StringUtils.isBlank(entity.getApplyWarehouseId())) {
            throw new BusinessException("对不起，请选择请领仓库！请领仓库为空，保存失败！");
        }

        if (StringUtils.isNotBlank(entity.getCode())) {
            int hitCount = service.count(Wrappers.<Warehouse>query()
                    .eq("code", entity.getCode())
                    .ne(!entity.isNewRecord(), "id", entity.getId()));
            if (hitCount > 0) throw new BusinessException("仓库代码重复，请换用其他代码");
        }


        boolean isOk = service.saveOrUpdate(entity);
        if (!isOk) {
            return RestResult.error("数据保存失败");
        }
        return RestResult.ok("数据保存成功", entity);
    }

    /**
     * 删除数据
     */
    @DeleteMapping("/delete")
    public RestResult deleteItems(@RequestBody Map<String, Object> para) {
        List<Serializable> ids = (List<Serializable>) para.get("ids");
        if(stockService.count(Wrappers.<Stock>query().in("warehouse_id",ids)) > 0) throw new BusinessException("该仓库已有库存记录，不允许删除");
        if(locationService.count(Wrappers.<Location>query().in("warehouse_id",ids)) > 0) throw new BusinessException("该仓库有下级库位，不允许删除");
        Boolean isOk = service.removeCascadeByIds(ids);
        if (!isOk) {
            return RestResult.error("数据删除失败");
        }
        return RestResult.ok("数据删除成功");
    }

    /**
     * 选择 获取数据列表
     */
    @GetMapping("/pageForSelect")
    public PageResult pageForSelect(@RequestParam Map<String, Object> reqData) {
        QueryContext queryContext = QueryContextHolder.currentContext();
        Map<String, Object> userParam =null;
        //固定参数
        if(reqData.containsKey("userParam")){
            JSONObject ob = JSON.parseObject(reqData.get("userParam")+"");
            userParam= Maps.newHashMap(ob);
        }

        //根据用户所有工位权限，筛选工位列表
        List<String> userWarehouseIdList = BeforeReport.getUserWarehouseIdList();
        if(userWarehouseIdList != null) {
            queryContext.getWrapper().in("id", BeforeReport.getUserWarehouseIdList());
        }else {
            queryContext.getWrapper().eq("1",0);
        }

        IPage<WarehouseSelectDto> pageResult = service.pageForSelect(queryContext,userParam);
        if (pageResult.getTotal() > 0) {
            List<String> warehouseIdList = pageResult.getRecords().stream().filter(tmp -> StringUtils.isNotBlank(tmp.getWarehouseId())).map(WarehouseSelectDto::getWarehouseId).distinct().collect(Collectors.toList());
            if (!warehouseIdList.isEmpty()) {
                List<Dept> deptList = deptService.list(Wrappers.<Dept>query().in("warehouse_id",warehouseIdList));
                if (!deptList.isEmpty()) {
                    Map<String,Dept> deptMap = deptList.stream().collect(Collectors.toMap(o -> o.getWarehouseId(), o -> o, (o1, o2) -> o1));
                    for (WarehouseSelectDto warehouseSelectDto : pageResult.getRecords()) {
                        if (deptMap.containsKey(warehouseSelectDto.getWarehouseId())) {
                            warehouseSelectDto.setDeptId(deptMap.get(warehouseSelectDto.getWarehouseId()).getId());
                            warehouseSelectDto.setDeptName(deptMap.get(warehouseSelectDto.getWarehouseId()).getName());
                        }
                    }
                }
            }
        }
        return PageResult.ok("查询成功", pageResult.getRecords(), pageResult.getTotal());
    }

    /**
     * 选择 获取数据列表
     */
    @GetMapping("/listForSelect")
    public RestResult listForSelect(@RequestParam Map<String, Object> reqData) {
        QueryContext queryContext = QueryContextHolder.currentContext();
        Map<String, Object> userParam =null;
        //固定参数
        if(reqData.containsKey("userParam")){
            JSONObject ob = JSON.parseObject(reqData.get("userParam")+"");
            userParam= Maps.newHashMap(ob);
        }

        //根据用户所有工位权限，筛选工位列表
        List<String> userWarehouseIdList = BeforeReport.getUserWarehouseIdList();
        if(userWarehouseIdList != null) {
            queryContext.getWrapper().in("id", BeforeReport.getUserWarehouseIdList());
        }else {
            queryContext.getWrapper().eq("1",0);
        }

        List<WarehouseSelectDto> listResult = warehouseMapper.listForSelect(queryContext.getWrapper(), queryContext.getParams(),userParam);
        if (listResult.size() > 0) {
            List<String> warehouseIdList = listResult.stream().filter(tmp -> StringUtils.isNotBlank(tmp.getWarehouseId())).map(WarehouseSelectDto::getWarehouseId).distinct().collect(Collectors.toList());
            if (!warehouseIdList.isEmpty()) {
                List<Dept> deptList = deptService.list(Wrappers.<Dept>query().in("warehouse_id",warehouseIdList));
                if (!deptList.isEmpty()) {
                    Map<String,Dept> deptMap = deptList.stream().collect(Collectors.toMap(o -> o.getWarehouseId(), o -> o, (o1, o2) -> o1));
                    for (WarehouseSelectDto warehouseSelectDto : listResult) {
                        if (deptMap.containsKey(warehouseSelectDto.getWarehouseId())) {
                            warehouseSelectDto.setDeptId(deptMap.get(warehouseSelectDto.getWarehouseId()).getId());
                            warehouseSelectDto.setDeptName(deptMap.get(warehouseSelectDto.getWarehouseId()).getName());
                        }
                    }
                }
            }
        }
        return RestResult.ok("查询成功", listResult);
    }

    /**
     * 将对没有默认仓库的科室创建相关仓库并进行绑定
     */
    @GetMapping("/creatByDept")
    @ThreadLock(busType = "creatByDept")
    public RestResult creatByDept() {
        return PageResult.ok(service.creatByDept(null));
    }
}
